package br.iesb.importer;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.filechooser.FileFilter;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.ContainerFactory;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;

import br.iesb.bean.Jogador;
import br.iesb.bean.Posicao;
import br.iesb.bean.Tabuleiro;
import br.iesb.bean.boat.ETipoEmbarcacao;
import br.iesb.bean.boat.ETiro;
import br.iesb.bean.boat.Embarcacao;

public class JSONImporter {

	public Tabuleiro loadFromJSON() {
		List<Embarcacao> embarcacoes = new ArrayList<Embarcacao>();
		List<Posicao> posicoes = new ArrayList<Posicao>();
		int qtSubmarinos = 0;
		int qtDestroyer = 0;
		int qtCruzador = 0;
		int qtPortavioes = 0;
		int qtEncouracado = 0;
		int qtLinha = 0;
		int qtColunas = 0;

		JSONParser parser = new JSONParser();
		JFileChooser chooser = new JFileChooser();
		chooser.setFileFilter(new FileFilter() {
			@Override
			public String getDescription() {
				return "Arquivo JSON";
			}

			@Override
			public boolean accept(File file) {
				return file.getName().toLowerCase().endsWith(".json");
			}
		});
		chooser.setMultiSelectionEnabled(false);
		
		if (JFileChooser.APPROVE_OPTION != chooser.showOpenDialog(null)) {
			JOptionPane.showMessageDialog(null, "Execução cancelada pelo usuário!", "Alerta", JOptionPane.ERROR_MESSAGE);
			System.exit(0);
		}
		
		File arquivo = chooser.getSelectedFile();
		try {
			Object obj = parser.parse(new FileReader(arquivo));
			JSONObject jsonObject = (JSONObject) obj;
			ContainerFactory containerFactory = new ContainerFactory() {
				public List creatArrayContainer() {
					return new LinkedList();
				}

				public Map createObjectContainer() {
					return new LinkedHashMap();
				}

			};
			JSONArray board = (JSONArray) jsonObject.get("tabuleiro");
			for (Object c : board) {
				try {
					Map json = (Map) parser.parse(c + "", containerFactory);
					Iterator iter = json.entrySet().iterator();
					System.out.println("==Tabuleiro==");
					while (iter.hasNext()) {
						Map.Entry entry = (Map.Entry) iter.next();
						String key = String.valueOf(entry.getKey());
						if (key.equals("qtSubmarinos")) {
							qtSubmarinos = Integer.parseInt(String
									.valueOf(entry.getValue()));
						} else if (key.equals("qtDestroyer")) {
							qtDestroyer = Integer.parseInt(String.valueOf(entry
									.getValue()));
						} else if (key.equals("qtCruzador")) {
							qtCruzador = Integer.parseInt(String.valueOf(entry
									.getValue()));
						} else if (key.equals("qtPortavioes")) {
							qtPortavioes = Integer.parseInt(String
									.valueOf(entry.getValue()));
						} else if (key.equals("qtEncouracado")) {
							qtEncouracado = Integer.parseInt(String
									.valueOf(entry.getValue()));
						} else if (key.equals("qtLinha")) {
							qtLinha = Integer.parseInt(String.valueOf(entry
									.getValue()));
						} else if (key.equals("qtColunas")) {
							qtColunas = Integer.parseInt(String.valueOf(entry
									.getValue()));
						}

						System.out.println(entry.getKey() + "=>"
								+ entry.getValue());
					}
				} catch (ParseException pe) {
					System.out.println(pe);
				}
			}

			JSONArray positions = (JSONArray) jsonObject.get("Posicoes");
			Posicao pos;
			for (Object c : positions) {
				try {
					Map json = (Map) parser.parse(c + "", containerFactory);
					Iterator iter = json.entrySet().iterator();
					System.out.println("==Posicao==");
					int linha = 0;
					int coluna = 0;
					String state = "";
					while (iter.hasNext()) {
						Map.Entry entry = (Map.Entry) iter.next();
						String key = String.valueOf(entry.getKey());
						if (key.equals("coluna")) {
							coluna = Integer.parseInt(String.valueOf(entry.getValue()));
						} else if (key.equals("linha")) {
							linha = Integer.parseInt(String.valueOf(entry.getValue()));
						} else if (key.equals("estado")) {
							state = String.valueOf(entry.getValue());
						}

						System.out.println(entry.getKey() + "=>"
								+ entry.getValue());
					}
					pos = new Posicao(linha, coluna, getStateEnum(state));
					posicoes.add(pos);
				} catch (ParseException pe) {
					System.out.println(pe);
				}
			}

			// loop array
			JSONArray boats = (JSONArray) jsonObject.get("Embarcacoes");
			Embarcacao emb;
			for (Object c : boats) {
				try {
					Map json = (Map) parser.parse(c + "", containerFactory);
					Iterator iter = json.entrySet().iterator();
					System.out.println("==Embarcacao==");
					String tipo = "";
					int linha = 0;
					int coluna = 0;
					boolean horizontal = false;
					String aux = "";

					while (iter.hasNext()) {
						Map.Entry entry = (Map.Entry) iter.next();
						String key = String.valueOf(entry.getKey());
						if (key.equals("posInicialLinha")) {
							linha = Integer.parseInt(String.valueOf(entry.getValue()));
						} else if (key.equals("posInicialColuna")) {
							coluna = Integer.parseInt(String.valueOf(entry.getValue()));
						} else if (key.equals("tipoNavio")) {
							tipo = String.valueOf(entry.getValue());
						} else if (key.equals("orientacaoHorizonta")) {
							aux = String.valueOf(entry.getValue());
							if (Boolean.getBoolean(aux)) {
								horizontal = true;
							}
						}
						System.out.println(entry.getKey() + "=>"
								+ entry.getValue());

					}
					emb = new Embarcacao(getEmbEnum(tipo));
					emb.setPosicaoInicial(new Posicao(linha, coluna));
					emb.setInHorizontal(horizontal);
					embarcacoes.add(emb);
					// System.out.println(JSONValue.toJSONString(json));
				} catch (ParseException pe) {
					System.out.println(pe);
				}
			}

		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (ParseException e) {
			e.printStackTrace();
		}

		Tabuleiro tabuleiro = new Tabuleiro(embarcacoes, posicoes, qtColunas,
				qtLinha, qtSubmarinos, qtDestroyer, qtCruzador, qtEncouracado,
				qtPortavioes);
		return tabuleiro;
	}

	public ETiro getStateEnum(String state) {
		if (state.equals("WATER")) {
			return ETiro.WATER;
		} else if (state.equals("HIT")) {
			return ETiro.HIT;
		} else {
			return ETiro.MISS;
		}
	}

	public ETipoEmbarcacao getEmbEnum(String state) {
		if (state.equals("Submarino")) {
			return ETipoEmbarcacao.SUBMARINO;
		} else if (state.equals("Destroyer")) {
			return ETipoEmbarcacao.DESTROYER;
		} else if (state.equals("Cruzador")) {
			return ETipoEmbarcacao.CRUZADOR;
		} else if (state.equals("Portaavioes")) {
			return ETipoEmbarcacao.PORTA_AVIOES;
		} else {
			return ETipoEmbarcacao.ENCOURACADO;
		}
	}

	public static void main(String[] args) {
		// new JSONImporter().importar(new
		// File("/Users/pedro/Desktop/arquivoFormatado.xml"));
		JSONImporter jn = new JSONImporter();
		Tabuleiro t = jn.loadFromJSON();

		Jogador player01 = new Jogador();
		player01.tiro(new Posicao(0,5), t);
		player01.tiro(new Posicao(1,5), t);
		player01.tiro(new Posicao(2,5), t);
		player01.tiro(new Posicao(3,5), t);
		player01.tiro(new Posicao(4,5), t);
		player01.tiro(new Posicao(5,5), t);
		player01.tiro(new Posicao(6,5), t);
		player01.tiro(new Posicao(7,5), t);
		player01.tiro(new Posicao(0,2), t);
		player01.tiro(new Posicao(1,2), t);
		player01.tiro(new Posicao(2,2), t);
		player01.tiro(new Posicao(3,2), t);
		player01.tiro(new Posicao(4,2), t);
		player01.tiro(new Posicao(5,2), t);
		player01.tiro(new Posicao(6,2), t);
		player01.tiro(new Posicao(7,2), t);
	}

}
